package com.ias.agdis_r.netservice;

import android.os.Handler;
import android.text.TextUtils;

import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.document.DocumentResult;
import com.ias.agdis_r.bean.other.IQRYInfoBean;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.terminalmanager.restful.bill.endpoint.request.BillGeneralRequest;
import com.ias.agdis_r.terminalmanager.restful.bill.vo.BillGeneralRequestVO;
import com.ias.agdis_r.terminalmanager.restful.findluggage.service.FindLuggageService;
import com.ias.agdis_r.terminalmanager.restful.message.endpoint.request.MessageTempletRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.FindForwardTaskRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.GetUnfinishedEventTaskListsRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.GetnewplantasklistsRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.GettaskbytnbRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.GetunfinishedtasklistsRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.QueryLuggageRequest;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.request.TaskTransferredRequest;
import com.ias.agdis_r.terminalmanager.restful.task.vo.FindForwardTaskRequestVO;
import com.ias.agdis_r.terminalmanager.restful.task.vo.GetTaskByTnbRequestVO;
import com.ias.agdis_r.terminalmanager.restful.task.vo.QueryLuggageRequestVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.request.WorkGroupLoadMembersRequest;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.network.HttpUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;


/**
 * IQRY信息发送线程
 * 
 * @author wanghu
 * 
 */
public class SendNormalIQRYThread extends Thread {

	private Handler handler;
	private long lSendIQRYinterval = 5*1000;
	private BillGeneralRequest billgeneralrequest;
	
	public SendNormalIQRYThread(Handler handler) {
		this.handler = handler;
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
	}

	@Override
	public void run() {
		if (ServiceManage.getInstance().getIsLogon()) {
			// 如果需要请求的restful的IP地址不为空
			if (S.isNotEmpty(RestfulUri.webIPAddress)) {
				// 发送IQRYX消息
				IQRYInfoBean iqryInfo = JavaBeanManager.getInstance().getIQRYinfo();

				/* 获取短语模板接口请求后，可能获取到的短语模板列表大小可能为0，但是短语模板信息已经初始化完成，心跳线程不再尝试获取短语模板信息 */
				// JavaBeanManager.getInstance().getMSGShort().isEmpty() && JavaBeanManager.getInstance().getMSGRemind().isEmpty()) {
				if (JavaBeanManager.getInstance().getMsgTempList() == null) {
					MessageTempletRequest request = new MessageTempletRequest();
					HttpUtil.getInstance().sendRequest(request, MessageModel.DYMB, false);
				}
				// 如果有西南清洁权限，初始化群组员工
				if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_WORKGROUP.toString()) && null == JavaBeanManager.getInstance().getWorkGroupLoadInfo()) {
					HttpUtil.getInstance().sendRequest(new WorkGroupLoadMembersRequest(), MessageModel.WGLM, false);
				}

				// 发送IQRYX消息
				LinkedHashMap<String,String> unfinishedTnbmap = DataManager.getInstance().getUnfinishedTnbMap();				// 未结束的任务tnbMap
				LinkedHashMap<String,String> unfinishedEventTnbmap = DataManager.getInstance().getUnfinishedEventTnbMap();		// 未结束的通用任务tnbMap
				LinkedHashMap<String,String> newTnbmap = DataManager.getInstance().getNewTnbMap();								// 未接收的任务tnbMap

				// 获取已转发任务列表(如果有已转任务，则需要在任务信息李增加“转发”标识)
				if (!"S".equals(iqryInfo.getGTFL()) && MessageModel.ZFYJ_TYPE_G.equals(JavaBeanManager.getInstance().getUserinfo().getTtr())) {
					HttpUtil.getInstance().sendRequest(initGTFL(), MessageModel.GTFL, false);
				}
				// 如果未完成任务的TNB列表不为空,请求TNB列表
				else if (unfinishedTnbmap == null) {
					GetunfinishedtasklistsRequest request = new GetunfinishedtasklistsRequest();
					HttpUtil.getInstance().sendRequest(request, MessageModel.FLG4, false);
				}
				// 如果有未完成的任务未获取成功
				else if (!unfinishedTnbmap.isEmpty()) {
					getTaskByTnbMap(unfinishedTnbmap);
				}
				// 如果未完成通用任务的TNB列表不为空,请求TNB列表
				else if(JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_EVENTTASK.toString()) && unfinishedEventTnbmap == null) {
					GetUnfinishedEventTaskListsRequest request = new GetUnfinishedEventTaskListsRequest();
					HttpUtil.getInstance().sendRequest(request, MessageModel.FLG41, false);
				}
				// 如果有未完成的任务未获取成功
				else if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_EVENTTASK.toString()) && !unfinishedEventTnbmap.isEmpty()) {
					getTaskByTnbMap(unfinishedEventTnbmap);
				}
				// 如果有清洁监控或任务记录权限，申请清洁监控内容
				else if(!"N".equals(iqryInfo.getIDXFLG10()) && (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_TASKMONITOR.toString())
						|| JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_TASKSEARCH.toString()))){
					HttpUtil.getInstance().sendRequest(initFLG10("1", null, iqryInfo.getIDXFLG10()) ,MessageModel.FLG10, false);
				}
				else {

					// 如果有打印单据权限,申请单据的版本信息
					if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_DOCPRINT.toString())) {
						new Thread(new Runnable() {
							@Override
							public void run() {
								LinkedHashMap<String, DocumentResult> docMap = new LinkedHashMap<>();
								docMap.putAll(DataManager.getInstance().getDocMap());
								for (Map.Entry<String, DocumentResult> entry : docMap.entrySet()) {
									String fke = entry.getKey();
									initBLRQ("", "", fke);
									HttpUtil.getInstance().sendRequest(billgeneralrequest, MessageModel.BLRQ, false);
									try {
										Thread.sleep(1000);
									} catch (InterruptedException e) {
										e.printStackTrace();
									}
								}
							}
						}).start();
					}
					// 获取翻行李信息
					if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_LUGGAGEFIND.toString())) {
						FindLuggageService.getFindLuggageInfo();
					}
					// 如果有行李条码权限,初始化任务条码信息
					if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_LUGGAGEBARCODE.toString()) && !JavaBeanManager.getInstance().isInitQueryLuggage()) {
						Set<String> tnbSet = DataManager.getInstance().getWorkTaskList().keySet();
						List<String> tnbList = new ArrayList<>(tnbSet);
						QueryLuggageRequest queryLuggageRequest = new QueryLuggageRequest();
						List<QueryLuggageRequestVO> list = new ArrayList<>();
						for (String tnb : tnbList) {
							QueryLuggageRequestVO queryLuggageRequestVO = new QueryLuggageRequestVO();
							queryLuggageRequestVO.setTnb(tnb);
							queryLuggageRequestVO.setEnb(JavaBeanManager.getInstance().getUserinfo().getEnb());
							list.add(queryLuggageRequestVO);
						}
						queryLuggageRequest.setList(list);
						HttpUtil.getInstance().sendRequest(queryLuggageRequest, MessageModel.QLBC, false);
					}

					// 修改IQRY发送时间间隔
					this.lSendIQRYinterval = 30 * 1000;

					// 检测是否有未下发的新任务
					if (newTnbmap == null || newTnbmap.isEmpty()) {
						GetnewplantasklistsRequest request = new GetnewplantasklistsRequest();
						HttpUtil.getInstance().sendRequest(request, MessageModel.FLG1, false);
					} else {
						// 如果有未下发的新任务，申请
						getTaskByTnbMap(newTnbmap);
					}
					// 如果有清洁监控或任务记录权限，申请清洁监控变更
					if(JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_TASKMONITOR.toString()) || JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_TASKSEARCH.toString())){
						HttpUtil.getInstance().sendRequest(initFLG10("0", iqryInfo.getSDXFLG10(), null) ,MessageModel.FLG10, false);
					}
				}
			}
		} else {
			Thread.interrupted();
		}
		handler.postDelayed(this, lSendIQRYinterval);
	}

	/**
	 * 根据tnbMap获取最后一个tnb，然后根据tnb获取任务信息。
	 * @param map tnbMap
	 */
	private void getTaskByTnbMap(Map<String, String> map) {
		if (map == null || map.isEmpty()) {
			return;
		}
		String tnbByMap = getTnbByMap(map);
		if (TextUtils.isEmpty(tnbByMap)) {
			return;
		}
		LinkedHashMap<String,String> requestTnbMap = new LinkedHashMap<>();
		requestTnbMap.put(tnbByMap, "");

		GettaskbytnbRequest request = new GettaskbytnbRequest();
		GetTaskByTnbRequestVO vo = new GetTaskByTnbRequestVO();
		vo.setHashmap(requestTnbMap);
		request.setGetTaskByTnbRequestVO(vo);

		HttpUtil.getInstance().sendRequest(request,MessageModel.TASK, false);
	}

	/**
	 * 根据tnbMap获取最后一个tnb。
	 * @param map tnbMap
	 * @return
	 */
	private String getTnbByMap(Map<String, String> map) {
		ListIterator<String> listIterator = new ArrayList<>(map.keySet()).listIterator(map.size());
		if (listIterator.hasPrevious()) {
			return listIterator.previous();
		}
		return null;
	}

	private void initBLRQ(String bno, String btp, String fkey) {
		billgeneralrequest = new BillGeneralRequest();
		BillGeneralRequestVO billgeneralrequestVO = new BillGeneralRequestVO();
		if (S.isNotEmpty(btp)) {
			billgeneralrequestVO.setBtp(btp);
		}
		if (S.isNotEmpty(bno)) {
			billgeneralrequestVO.setBno(bno);
		}
		billgeneralrequestVO.setFkey(fkey);
		billgeneralrequest.setBillGeneralRequestVO(billgeneralrequestVO);
	}

	private FindForwardTaskRequest initFLG10(String ini, String ptm, String idx){
		FindForwardTaskRequest findForwardTaskRequest = new FindForwardTaskRequest();
		FindForwardTaskRequestVO findForwardTaskRequestVO = new FindForwardTaskRequestVO();
		findForwardTaskRequestVO.setIni(ini);
		if (S.isNotEmpty(ptm)){
			findForwardTaskRequestVO.setPtm(ptm);
		}
		if (S.isNotEmpty(idx)){
			findForwardTaskRequestVO.setIdx(idx);
		}
		findForwardTaskRequest.setFindForwardTaskRequestVO(findForwardTaskRequestVO);
		return findForwardTaskRequest;
	}

	private TaskTransferredRequest initGTFL(){
		TaskTransferredRequest taskTransferredRequest = new TaskTransferredRequest();
		return taskTransferredRequest;
	}
}
